package com.xiangxiangjd.aircraftanalysis.config.token;

import io.jsonwebtoken.*;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.Date;
import java.util.Map;

@Data
@ConfigurationProperties(value = "jwt.config")
public class JwtUtils   {


    //签名私钥
    private String key;

    //签名的失效时间
    private Long ttl;

    /**
     * 认证token
     *
     * @param nid   用户ID
     * @param name 登录用户名
     * @param map
     * @return
     */
    public String createJwt(Integer nid, String name, Map<String, Object> map) {


        String id = String.valueOf(nid);

        //1.设置失效时间
        long now = System.currentTimeMillis();//当前毫秒数
        long exp = now + ttl;

        // 2.创建jwtBuilder
        JwtBuilder jwtBuilder = Jwts.builder().   //生存token
                setId(id). //id赋值
                setSubject(name).//用户
                setIssuedAt(new Date()). //存入时间
                signWith(SignatureAlgorithm.HS256, key);


        //3.更具map设置claims

        //map.entrySet()返回键值对   遍历键值对

        for (Map.Entry<String, Object> entry : map.entrySet()) {
            jwtBuilder.claim(entry.getKey(), entry.getValue());

        }


        jwtBuilder.setExpiration(new Date(exp));//失效时间
        // 4.创建token

        String token = jwtBuilder.compact();

        return token;
    }

    /**
     * 解析token
     */

    public Claims parseJwt(String token) {

        try {
            Claims claims = Jwts.parser().setSigningKey(key).//解析名字
                    parseClaimsJws(token).getBody();

            System.out.println(claims.toString());

            long now = System.currentTimeMillis();//当前毫秒数
            long exp = now + ttl;

            claims.setExpiration(new Date(exp));
            return claims;
        //捕捉过期token
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("token 过期");
            return null;
        }



    }


}
